package com.bidevalution.business.impl;

import com.bidevalution.business.dto.BeSectionEnterpriseDto;
import com.bidevalution.business.service.BeBidFileService;
import com.bidevalution.dao.entity.BeBidFile;
import com.bidevalution.dao.entity.BeSectionEnterprise;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.mapper.BeBidFileMapper;
import com.bidevalution.dao.mapper.BeSectionEnterpriseMapper;
import com.bidevalution.dao.mapper.BeSectionInfoMapper;
import com.bidevalution.support.context.Constants;
import com.qtp.core.common.HttpTookit;
import com.qtp.core.model.RemoteResponse;
import com.qtp.core.model.Response;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.GsonUtil;
import com.qtp.core.util.OConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class BeBidFileServiceImpl implements BeBidFileService{

	private static final String HIDDEN_NUM = "****";

	private static final Logger log = LoggerFactory.getLogger(BeBidFileServiceImpl.class);

	@Autowired(required = false)
	private BeBidFileMapper beBidFileMapper;
	@Autowired(required = false)
	private BeSectionInfoMapper beSectionInfoMapper;
	@Autowired(required = false)
	private BeSectionEnterpriseMapper beSectionEnterpriseMapper;
	@Value("${authLoginUrl}")
	private String authLoginUrl;
	@Override
	@Transactional
	public int insertSelective(BeBidFile record) {
		// TODO Auto-generated method stub
		return beBidFileMapper.insertSelective(record);
	}

	@Override
	public BeBidFile selectByPrimaryKey(String fileId) {
		// TODO Auto-generated method stub
		return beBidFileMapper.selectByPrimaryKey(fileId);
	}

	@Override
	public int updateByPrimaryKey(BeBidFile record) {
		return beBidFileMapper.updateByPrimaryKey(record);
	}

	@Override
	public List<BeSectionInfo> selectByOrgCode(String orgCode,String startDate,String endDate) {
		// TODO Auto-generated method stub
		return beSectionInfoMapper.getListByOrgCode(orgCode,DateUtil.stringToDate(startDate+" 00:00:00", "yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate+" 23:59:59", "yyyy-MM-dd HH:mm:ss"));
	}

	@Override
	public Response<List<BeSectionEnterpriseDto>> selectBySectionId(String sectionId, String enterpriseName, String userLoginName, String password) {
		List<BeSectionEnterprise> list = beSectionEnterpriseMapper.selectBySectionId(sectionId);
		List<BeSectionEnterpriseDto> dataList = new ArrayList<>();
		boolean passwordIsRight = showHiddenNum(userLoginName, password);
		/** begin:2020-04-01 夏云飞 需求 二阶段导入列表改造 */
		if (list != null && !list.isEmpty()) {
			for (BeSectionEnterprise ent : list) {
				BeSectionEnterpriseDto dto = new BeSectionEnterpriseDto();
				dto.setSeqId(ent.getSeqId());
				dto.setSectionId(ent.getSectionId());
				dto.setEnterpriseName(ent.getEnterpriseName());
				dto.setPrice(ent.getPrice());
				dto.setQualityPromise(ent.getQualityPromise());
				dto.setJsImportDate(ent.getJsImportDate());
				dto.setSwImportDate(ent.getSwImportDate());
				if (!passwordIsRight) {
					dto.setBidHideNumber(HIDDEN_NUM);
				} else {
					dto.setBidHideNumber(ent.getBidHideNumber());
				}
				int importResult = OConvertUtils.getInt(ent.getImportResult(),Constants.ZERO);
				int step = Constants.ONE;
				dto.setJsImportStatus(getImportStatus(importResult, step++));
				dto.setSwImportStatus(getImportStatus(importResult, step++));
				dto.setBidProjectid(ent.getBidProjectid());

				dataList.add(dto);
			}
		}
		/** end:2020-04-01 夏云飞 需求 二阶段导入列表改造 */
		Response<List<BeSectionEnterpriseDto>> rsp;
		if (StringUtils.isBlank(password) || passwordIsRight) {
			rsp = Response.ok(dataList);
		} else {
			rsp = new Response<>();
			rsp.setError("密码错误");
			rsp.setResult(dataList);
			rsp.setStatus(200);
		}
		return rsp;
	}

	/**
	 * 导入状态
	 *
	 * @param importResult
	 * @param step
	 * @return
	 */
	private String getImportStatus(int importResult, int step) {
		// 未导入
		if (importResult < step * 2 - 1) {
			return "";
		}
		return importResult >= step * 2 ? "成功" : "失败";
	}

	@Override
	public List<BeBidFile> findErrorBidFileList(String startDate, String endDate) {
		return beBidFileMapper.findErrorBidFileList(DateUtil.stringToDate(startDate+" 00:00:00", "yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate+" 23:59:59", "yyyy-MM-dd HH:mm:ss"));
	}

	private boolean showHiddenNum(String userLoginName,String password) {
		if(StringUtils.isBlank(password)||StringUtils.isBlank(userLoginName)) {
			return false;
		}
		Map<String, Object> params = new HashMap<>(8);
		params.put("loginType", 1);
		params.put("userName", userLoginName);
		params.put("userPassword", password);
		try {
			log.info("获取投标列表，验证密码：userLoginName="+userLoginName+"，password="+password);
			RemoteResponse result = HttpTookit.doPost(authLoginUrl + "/login/login.do", params);
			log.info("获取投标列表，验证密码返回结果："+ GsonUtil.toJson(result));
			String content = result.getContent();
			Response rsp = GsonUtil.parseJsonWithGson(content, Response.class);
			return rsp.isSuccess();
		} catch (Exception e) {
			log.error("验证密码失败", e);
		}
		return false;
	}

}
